#include "weather.h"
#include "ui_weather.h"
#include <QFile>
#include <QDebug>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QJsonValue>


Weather::Weather(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Weather)
{
    ui->setupUi(this);

    //准备城市编号
    init_citykey();

    //关联请求finished信号
    connect(&manager,&QNetworkAccessManager::finished,this,&Weather::read_data);

    //创建天气显示界面
    items = new Form[5];
    //把items添加到widget容器中的weatherHBox中
    for(int i = 0;i<5;i++)
    {
        ui->weatherHBox->addWidget(&items[i]);
    }
}

void Weather::init_citykey()
{
    QFile file(":/citykeys.txt");
    file.open(QIODevice::ReadOnly);   //打开文件
    QString data = file.readAll();   //读取文件数据
    file.close();//关闭文件

    data.remove("\"");//删除"
    QStringList list = data.split(",");  //把数据以,分割
    for(int i = 0;i<list.size();i++)
    {
        //101010100:北京  -- list.at(0)
        QString tmp = list.at(i);
        QStringList tmplist = tmp.split(":");

        if(tmplist.size() == 2)
            citykey.insert(tmplist.at(1),tmplist.at(0));  //城市名，城市编号

    }


    qDebug()<<list.size();

}


Weather::~Weather()
{
    delete ui;
}

void Weather::on_updateBt_clicked()
{
    //获取城市名
    QString cityname = ui->cityEdit->text();
    //qDebug()<<cityname<<citykey.value(cityname);

    QString urlstr = QString("http://t.weather.sojson.com/api/weather/city/%1").arg(citykey.value(cityname));

    //请求天气数据
    QUrl url(urlstr);
    QNetworkRequest request(url);
    manager.get(request);





}

void Weather::read_data(QNetworkReply *reply)
{
    QByteArray array = reply->readAll();  //读取所有数据

    // 把array数据通过document转换为json对象
    QJsonParseError err;
    QJsonDocument doc = QJsonDocument::fromJson(array,&err);
    if(err.error!=QJsonParseError::NoError)
    {
        qDebug()<<"json err";
        return;
    }
    //转为json对象
    QJsonObject obj = doc.object();
    QJsonObject dataObj = obj.value("data").toObject();
    QJsonArray forecastArray = dataObj.value("forecast").toArray();


    QString shidu = dataObj.value("shidu").toString(); //湿度
    QString pm25 = QString::number(dataObj.value("pm25").toDouble()); //pm2.5


    if(forecastArray.size()<5)
    {
        return;
    }
    for(int i = 0;i<5;i++)
    {
        //获取数组中的前五个对象
        QJsonObject forecastArrayObj = forecastArray.at(i).toObject();


        QString ymd = forecastArrayObj.value("ymd").toString();//日期
        QString high = forecastArrayObj.value("high").toString(); //最高温度
        QString low = forecastArrayObj.value("low").toString(); //最低温度

        items[i].set_weather(ymd,high,low,shidu,pm25);

    }

}
